package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.exception.ServiceException;
import com.qs.model.entity.User;
import com.qs.mapper.UserMapper;
import com.qs.model.vo.UserVo;
import com.qs.response.ResponseEnum;
import com.qs.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.utils.EncryptUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void updateUserInfo(UserVo userVo) {
        User user = baseMapper.selectById(userVo.getId());
        if(null == user) {
            throw new ServiceException(ResponseEnum.BAD_REQUEST);
        }
        if(!user.getNickName().equalsIgnoreCase(userVo.getNickName())){
            QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("nick_name", userVo.getNickName());
            Long count = baseMapper.selectCount(wrapper);
            if(count > 0){
                throw new ServiceException(ResponseEnum.USER_EXITS);
            }
        }
        if(user.getPassword().equalsIgnoreCase(userVo.getPassword())){
            user.setNickName(userVo.getNickName());
            user.setAvatar(userVo.getAvatar());
            baseMapper.updateById(user);
        }else{
            String newPassword = EncryptUtils.MD5Password(userVo.getPassword());
            user.setPassword(newPassword);
            user.setNickName(userVo.getNickName());
            user.setAvatar(userVo.getAvatar());
            baseMapper.updateById(user);
        }
    }
}
